package cn.zwx.remoting;

import cn.zwx.remoting.netty.InvokeCallback;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 返回参数封装
 * @author 105286
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class ResponseFuture {
    /**
     *  请求ID
     **/
    private String xid;
    private long timeoutMillis;
    private InvokeCallback callback;
    private long beginTimestamp = System.currentTimeMillis();
    private CountDownLatch countDownLatch = new CountDownLatch(1);
    private volatile RemotingCommand command;
    private volatile boolean sendRequestOk;
    private volatile Throwable cause;
    private final AtomicBoolean executeCallbackOnlyOnce = new AtomicBoolean(false);

    public ResponseFuture(String xid, long timeoutMillis, InvokeCallback callback) {
        this.xid = xid;
        this.timeoutMillis = timeoutMillis;
        this.callback = callback;
    }

    /**
     * 延迟返回
     * @param timeoutMillis 超时时间
     * @return cn.zwx.remoting.RemotingCommand
     * @author zhangwenxue
     * @createTime 2022/6/20 11:03
     **/
    public RemotingCommand waitResponse(final long timeoutMillis) throws InterruptedException {
        this.countDownLatch.await(timeoutMillis, TimeUnit.MILLISECONDS);
        return this.command;
    }

    /**
     *  释放资源
     * @return void
     * @author zhangwenxue
     * @createTime 2022/6/20 11:03
     **/
    public void release() {
        if (Objects.nonNull(countDownLatch)){
            countDownLatch.countDown();
        }
    }


    /**
     * putResponse
     * @param remotingCommand  remotingCommand
     * @return void
     * @author zhangwenxue
     * @createTime 2022/6/20 11:03
     **/
    public void putResponse(final RemotingCommand remotingCommand) {
        this.command = remotingCommand;
        this.countDownLatch.countDown();
    }


    /**
     *  调用callback方法
     * @return void
     * @author zhangwenxue
     * @createTime 2022/6/20 11:01
     **/
    public void executeInvokeCallback() {
        if (callback != null) {
            if (executeCallbackOnlyOnce.compareAndSet(false, true)) {
                callback.operationComplete(this);
            }
        }
    }
}
